package com.dsunsoft.rtu.web;

import com.dsunsoft.rtu.entity.HeartbeatInfo;
import com.dsunsoft.rtu.netty.NettyHeartbeatMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/")
public class IndexController {

    @RequestMapping("")
    public String get() {
        return "hello world";
    }

    @GetMapping(value = "/heartbeat")
    public List<HeartbeatInfo> getDevices() throws IOException {
        List<HeartbeatInfo> heartbeatList = new ArrayList<>();
        Map<Integer, HeartbeatInfo> channelMap = NettyHeartbeatMap.get();
        for (Map.Entry<Integer, HeartbeatInfo> entry : channelMap.entrySet()) {
            heartbeatList.add(entry.getValue());
        }
        if (!CollectionUtils.isEmpty(heartbeatList)) {
            heartbeatList = heartbeatList.stream().sorted(Comparator.comparing(HeartbeatInfo::getLastReportDate).reversed())
                    .collect(Collectors.toList());
        }
        return heartbeatList;
    }
}
